package org.o14x.alpha.ui.views.foldertree;

import java.io.File;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;

/**
 * ContentProvider for the folder tree.
 * 
 * @author Olivier DANGREAUX
 */
public class FolderTreeContentProvider implements ITreeContentProvider {
	
	@Override
	public Object[] getChildren(Object parentElement) {
		Object[] children = null;

		if (parentElement instanceof FolderTreeInput) {
			children = ((FolderTreeInput) parentElement).getRootsArray();
		} else {
			File parentFile = (File) parentElement;
			if (parentFile.isDirectory()) {
				children = parentFile.listFiles();
			}
		}

		return children;
	}

	@Override
	public Object getParent(Object element) {

		if (element instanceof FolderTreeInput) {
			return null;
		} else {
			File file = (File) element;
			return file.getParentFile();
		}
	}

	@Override
	public boolean hasChildren(Object element) {
		if (element instanceof FolderTreeInput) {
			return ((FolderTreeInput) element).getRoots().size() > 0;
		} else {
			File file = (File) element;
			if (file.isDirectory()) {
				return file.listFiles() != null && file.listFiles().length != 0;
			}
		}

		return false;
	}

	@Override
	public Object[] getElements(Object inputElement) {
		return getChildren(inputElement);
	}

	@Override
	public void dispose() {
	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
	}
}
